package com;

import com.spire.xls.*;
import com.spire.xls.collections.WorksheetsCollection;

import java.awt.*;
import java.awt.image.BufferedImage;

import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

//实现水印效果！！  传输的时候可以不要一直读取读取，我们可以通过传递workbook的方式进行读取。！！
//https://www.e-iceblue.cn/
public class ExcelWatermark {
    public static void main(String[] args) {
        //加载示例文档
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\order1.xls");
        //设置文本和字体大小
        Font font = new Font("仿宋", Font.PLAIN, 50);
        String watermark = "富建商行";
        WorksheetsCollection worksheets = workbook.getWorksheets();
        Worksheet sheet = worksheets.get(0);
        BufferedImage imgWtrmrk = drawText(watermark, font, Color.PINK, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());
        sheet.getPageSetup().setBackgoundImage(imgWtrmrk);
        //将显示模式设置为Normal  正常的就可以了。
        sheet.setViewMode(ViewMode.Normal);
        //保存文档
        workbook.saveToFile("C:\\Users\\Administrator\\Desktop\\order2.xls", ExcelVersion.Version97to2003);
    }
    /**
     * @param text  水印文字
     * @param font  字体样式
     * @param textColor  字体颜色
     * @param backColor  背景颜色
     * @param height   高度
     * @param width    宽度
     */
    private static BufferedImage drawText(String text, Font font, Color textColor, Color backColor, double height, double width) {
        //定义图片宽度和高度
        BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);
        Graphics2D loGraphic = img.createGraphics();

        //获取文本size
        FontMetrics loFontMetrics = loGraphic.getFontMetrics(font);
        int liStrWidth = loFontMetrics.stringWidth(text);
        int liStrHeight = loFontMetrics.getHeight();

        //文本显示样式及位置
        loGraphic.setColor(backColor);
        loGraphic.fillRect(0, 0, (int) width, (int) height);
        loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
        loGraphic.rotate(Math.toRadians(-45));

        loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2);
        loGraphic.setFont(font);
        loGraphic.setColor(textColor);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
        loGraphic.dispose();
        return img;
    }
}